﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Abp.Domain.Repositories;
using KelonProud.Administration.Domain.Authorization;
using KelonProud.Linq;
using Microsoft.AspNetCore.Hosting;

namespace KelonProud.Administration.Managers.Authorization
{
    public class AttachmentManager: KelonProudDomainService<Attachment, int>
    {
        private readonly IHostingEnvironment _hostingEnvironment;

        public AttachmentManager(IRepository<Attachment, int> manageRepository, 
            IHostingEnvironment hostingEnvironment) : base(manageRepository)
        {
            _hostingEnvironment = hostingEnvironment;
        }

        public Attachment SaveOnFileFolder(string displayName, string contentType,string folderPath, int size)
        {
            var attachment = new Attachment()
            {
                FileName = GetFileName(),
                DisplayName = displayName,
                ContractionsFileName=displayName,//缩略图(暂未实现)
                ContentType = contentType,
                FileFolderPath = folderPath,
                SizeKb = size,
                FileExtension = Path.GetExtension(displayName),
            };
            attachment.Id = ManagerRepository.InsertAndGetId(attachment);

            return attachment;
        }

        public override void Delete(int id)
        {
            var attachment = GetById(id);
            //删除附件，如果存文件,且路径不为空，则连文件一并删除
            if (attachment != null)
            {
                    var fileFloderPath = attachment.FileFolderPath;
                    if (fileFloderPath != null)
                    {
                        var loclPath = _hostingEnvironment.WebRootPath + fileFloderPath;

                        var path = string.Concat(loclPath, attachment.FileName + attachment.FileExtension);
                        if (File.Exists(path)) File.Delete(path);
                    }

               ManagerRepository.Delete(attachment);
            }
        }

        public void Update(Attachment attachment)
        {
            if (attachment != null)
            {
                ManagerRepository.Update(attachment);
            }
        }

        public void Insert(Attachment attachment)
        {
            ManagerRepository.Insert(attachment);
        }

        private string GetFileName()
        {
            return "{0}_{1}".FormatWith(AbpSession.UserId, Guid.NewGuid().ToString("N"));
        }

        public List<Attachment> GetFileList(string ids)
        {
            List<Attachment> attList = new List<Attachment>();
            var idArr = ids.Split(",").ToList();
            if(idArr!=null&&idArr.Count>0)
            {
                attList= ManagerRepository.GetAllList(p => idArr.Contains(p.Id.ToString()));
            }
            return attList;
        }
    }
}
